package edu.fhsu.csci468;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;


public class SensorServer implements ISensorEventListener, Runnable
{

	int maxSensorsClients;
	private Hashtable<Integer, Sensor> sensors;	
	private ISensorEventListener he;
	
	public SensorServer(ISensorEventListener he)
	{
		this.he = he;
		sensors = new Hashtable<Integer, Sensor>();
	}
	
	
	public void run()
	{
		try
		{
			int id=1;
			ServerSocket s = new ServerSocket(Ports.SENSOR_PORT);
			
			while (true)
			{
				Socket incoming = s.accept();
				Sensor newSensor = new Sensor(incoming, id);
				(new Thread(newSensor)).start();
				newSensor.addSensorEventListener(this);
				newSensor.addSensorEventListener(he);
				sensors.put(id, newSensor);
				
				System.out.println("Spawning Sensor " + id);
				id++;
			}
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public void sensorEventOccurred(SensorEvent evt)
	{
		if(evt.getSensorAction() == SensorAction.Discontect )
		{
			// If a sensor is lost get rid of it
			// need to warn someone
			sensors.remove(evt.getSensorID());
			System.out.println("Removing sensor " + evt.getSensorID());

		}
	}
	
}
